package com.github.rnewson.couchdb.lucene.index;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.*;

public abstract class BaseWriter {
	Directory dir;
	IndexWriter indexWriter;

	public BaseWriter(String indexP) {
		try {
			dir = FSDirectory.open(new File(indexP));

			indexWriter = new IndexWriter(dir, new StandardAnalyzer(
					Version.LUCENE_20), new MaxFieldLength(10008));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public BaseWriter() {

	}

	public void setIndex(String index) {
		try {
			dir = FSDirectory.open(new File(index));

			indexWriter = new IndexWriter(dir, new StandardAnalyzer(
					Version.LUCENE_20), new MaxFieldLength(1000));

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addNewDoc(Document d) {
		try {
			indexWriter.addDocument(d);
			indexWriter.commit();
			indexWriter.optimize();
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void closeIndex() {
		
		try {
			//indexWriter.unlock(dir);
			dir.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			
			indexWriter.close();
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		dir = null;
		indexWriter = null;
	}

}
